package io.renren.modules.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import io.renren.common.exception.RRException;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddOrderGroup;
import io.renren.common.validator.group.CheckCarGroup;
import io.renren.common.validator.group.UpdateOrderGroup;
import io.renren.modules.app.PicSuffix;
import io.renren.modules.app.config.AlipayConfigs;
import io.renren.modules.app.entity.AgentEntity;
import io.renren.modules.app.entity.AlipayNotifyEntity;
import io.renren.modules.app.entity.OrderEntity;
import io.renren.modules.app.entity.UserCarEntity;
import io.renren.modules.app.form.CheckCarForm;
import io.renren.modules.app.form.OrderForm;
import io.renren.modules.app.form.OrderPOJO;
import io.renren.modules.app.form.PayOrderForm;
import io.renren.modules.app.service.AgentService;
import io.renren.modules.app.service.AlipayNotifyService;
import io.renren.modules.app.service.OrderService;
import io.renren.modules.app.service.UserCarService;
import io.renren.modules.app.utils.FileUtils;
import io.renren.modules.app.utils.OrderUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Auther zxl
 * @Date 2018/12/17 14:27
 * @Description
 **/
@RestController
@RequestMapping("/app/check")
public class AppOrderController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private OrderService orderService;
    @Autowired
    private AgentService agentService;
    @Autowired
    private UserCarService userCarService;
    @Autowired
    AlipayNotifyService alipayNotifyService;

    @Autowired
    AlipayConfigs alipayConfigs;
    /**
     * 图片路径
     */
    @Value("${check-car.orderBeforePicPath}")
    String orderBeforePicPath;
    /**
     * 图片路径
     */
    @Value("${check-car.orderAfterPicPath}")
    String orderAfterPicPath;
    private final ResourceLoader resourceLoader;

    @Autowired
    public AppOrderController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    /**
     * 用户下单
     * @param orderForm
     * @return
     */
    @PostMapping("addOrder")
    public R addOrder(@RequestBody OrderForm orderForm, HttpServletRequest request){

        ValidatorUtils.validateEntity(orderForm, AddOrderGroup.class);

        Long userId = (Long)request.getAttribute("userId");
        if (userId == null){
            return R.error("请先登陆");
        }
        if(orderForm.getAgentId()==null){
            return R.error("agentId不能为空");
        }
        System.out.println("userId:"+userId);
        List<OrderEntity> list = orderService.selectOrderNotClose(userId);
        if (list != null && list.size()>0){
            System.out.println("size:"+list.size());
            return R.error("您已有未处理的订单，可以到我的当前订单页面中取消订单。");
        }
        AgentEntity agentEntity = agentService.queryById(orderForm.getAgentId());
        UserCarEntity userCarEntity = userCarService.queryOneByUserId(userId);
        int carType = userCarEntity.getCarType();
        String car_type = "七座汽车";
        double base_money = agentEntity.getBigPrice();
        if (carType==5){
            base_money = agentEntity.getSmallPrice();
            car_type = "五座汽车";
        }
        String order_subject = agentEntity.getAgentName();
        //运营车
        Double operate_price = 0.00;
        Double order_money = base_money;
        if (userCarEntity.getOperateCar() == 1){
            operate_price = agentEntity.getOperatePrice();
            order_money += operate_price;
            order_subject=order_subject+" "+car_type+" 运营车检车服务";
        }else {
            order_subject=order_subject+" "+car_type+" 非运营车检车服务";
        }
        OrderEntity orderEntity = new OrderEntity(orderForm);
        orderEntity.setCreateTime(new Date());
        orderEntity.setUserId(userId);
        orderEntity.setOrderMoney(order_money);
        orderEntity.setOrderSubject(order_subject);
        String orderId = OrderUtils.generateOrderId(userId+"_");
        orderEntity.setOrderId(orderId);
        boolean b =  orderService.addOrder(orderEntity);
        if (b) {
            PayOrderForm payOrderForm = new PayOrderForm();
            payOrderForm.setOrderId(orderId);
            payOrderForm.setOrderMoney(order_money);
            payOrderForm.setOrderSubject(order_subject);
            payOrderForm.setOrderTime(orderEntity.getOrderTime());
            payOrderForm.setBasePrice(base_money);
            payOrderForm.setOperatePrice(operate_price);
            logger.info("生成订单："+payOrderForm.toString());
            return R.ok().put("data",payOrderForm);
        }
        return R.error("下单失败");
    }

    /**
     * 更新订单
     * @param orderForm
     * @param request
     * @return
     */
    @PostMapping("/updateOrder")
    public R update(@RequestBody OrderForm orderForm, HttpServletRequest request){


        ValidatorUtils.validateEntity(orderForm, UpdateOrderGroup.class);
        long userId = (Long)request.getAttribute("userId");
        OrderEntity old_orderEntity = orderService.getOneByOrderId(orderForm.getOrderId());
        if (old_orderEntity == null){
            return R.error("订单不存在");
        }else if (old_orderEntity.getOrderState()>3){
            return R.error("订单不可修改");
        }
        UserCarEntity userCarEntity = userCarService.queryOneByUserId(userId);
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderId(orderForm.getOrderId());
        if (orderForm.getAgentId() != null){
            if (old_orderEntity.getOrderState() == 3){
                // 配单成功
                return R.error("您已经配单成功，不可更换代理商！");
            }
            orderEntity.setAgentId(orderForm.getAgentId());
            AgentEntity agentEntity = agentService.queryById(orderForm.getAgentId());
            String subject = agentEntity.getAgentName()
                    +(userCarEntity.getCarType()==5 ? " 五座汽车" : " 七座汽车")
                    +(userCarEntity.getOperateCar() == 1 ? " 运营车" : " 非运营车")
                    +"检车服务";
            orderEntity.setOrderSubject(subject);
        }
        if (orderForm.getOrderTime() != null){
            orderEntity.setOrderTime(orderForm.getOrderTime());
        }
        if(old_orderEntity.getOrderState() == 3){
            // 已经配单成功,修改状态为 订单修改
            orderEntity.setOrderState(10);
        }
        boolean b = orderService.updateOrder(orderEntity);
        if (b){
            return R.ok("修改成功,等待代理商确认");
        }
        return R.error();

    }

    /**
     * 取消订单
     * @param request
     * @param orderId
     * @return
     */
    @GetMapping("/cancelOrder")
    public R cancelOrder(HttpServletRequest request,
                         @RequestParam(value = "orderId",required = true) String orderId) throws AlipayApiException {

        OrderEntity orderEntity = orderService.getOneByOrderId(orderId);
        if (orderEntity == null){
            return R.error("订单不存在");
        }else if (orderEntity.getOrderState() == 4){
            return R.error("已开始检车，不能取消订单！");
        }else if (orderEntity.getOrderState() < 4){
            boolean b =  orderService.cancelOrder(orderId);
            if (b){
                if (orderEntity.getOrderState() > 1){
                    // 退款
                    AlipayNotifyEntity alipayNotifyEntity = alipayNotifyService.getOne(orderEntity.getOrderId());
                    if (alipayNotifyEntity!=null){
                        // 支付宝退款
                        String res = alipayConfigs.refund(alipayNotifyEntity);
                        JSONObject jsonObject = JSONObject.parseObject(
                                JSONObject.parseObject(res).getString("alipay_trade_refund_response"));
                        logger.warn("支付宝退款："+res);
                        logger.error("jsonObject:"+jsonObject.toJSONString());
                        String return_code = jsonObject.getString("code");
                        if (StringUtils.equals(return_code,"10000")){
                            // 退款成功
                            double fee = Double.parseDouble(jsonObject.getString("refund_fee"));
                            AlipayNotifyEntity notifyEntity = new AlipayNotifyEntity();
                            alipayNotifyEntity.setOrderId(notifyEntity.getOrderId());
                            alipayNotifyEntity.setRefundFee(fee);
                            alipayNotifyEntity.setRefundTime(new Date());
                            boolean b_update = alipayNotifyService.update(alipayNotifyEntity);
                            logger.info(alipayNotifyEntity.getOrderId()+"，退款更新refund_fee："+fee+" / "+b_update);
                            return R.ok("订单取消成功，完成支付宝退款金额："+fee
                                        +"到支付宝账户："+jsonObject.getString("buyer_logon_id"));
                        }else {
                            return R.ok("订单取消失败,"+jsonObject.getString("sub_msg")+"，完成支付宝退款RMB："+jsonObject.getString("refund_fee")+",请重试！");
                        }
                    }
                    return R.ok("订单取消成功...");
                }
                return R.ok("订单取消成功");
            }
        }else {
            R.error("订单不能取消");
        }
        return R.error("订单取消失败");

    }

    /**
     * 查询用户订单
     * @param request
     * @param type  0: 未处理订单，1：所有订单
     * @return
     */
    @GetMapping("/userOrders")
    public R userOrders(HttpServletRequest request,@RequestParam(required = true,defaultValue = "1") String type){

        System.out.println("type:"+type);
        long userId = (Long)request.getAttribute("userId");
        Integer int_type = Integer.parseInt(type);
        List<OrderEntity> list;
        if (int_type == 0){
            // 未结束的订单
            list = orderService.selectOrderNotClose(userId);
        }else {
            // 所有订单
            list = orderService.selectOrders(userId);
        }
        if (list == null || list.size()==0){
            return R.error("没有订单");
        }
        List<OrderPOJO> res = new ArrayList<>(list.size());
        OrderPOJO orderPOJO ;
        for (OrderEntity orderEntity:list) {
            orderPOJO = new OrderPOJO();
            orderPOJO.setOrderEntity(orderEntity);
            orderPOJO.setUserCarEntity(userCarService.queryOneByUserId(userId));
            orderPOJO.setAgentEntity(agentService.queryById(orderEntity.getAgentId()));
            orderPOJO.setAlipayNotifyEntity(alipayNotifyService.getOne(orderEntity.getOrderId()));
            res.add(orderPOJO);
        }
        return R.ok().put("data",res);
    }

    /**
     * 获取order
     * @param request
     * @param orderId
     * @return
     */
    @GetMapping("/getOrder")
    public R getOrder(HttpServletRequest request,@RequestParam(required = true,value = "orderId") String orderId){

        long userId = (Long)request.getAttribute("userId");
        if (StringUtils.isBlank(orderId)){
            return R.error("订单号不能为空");
        }
        OrderEntity orderEntity =orderService.getOneByOrderId(orderId);
        if (orderEntity == null){
            return R.error("订单号无效");

        }
        OrderPOJO orderPOJO =  new OrderPOJO();
        orderPOJO.setOrderEntity(orderEntity);
        orderPOJO.setUserCarEntity(userCarService.queryOneByUserId(userId));
        orderPOJO.setAgentEntity(agentService.queryById(orderEntity.getAgentId()));

        return R.ok().put("data",orderPOJO);




    }

    /**
     * 检车前上传照片
     * @param file
     * @param request
     * @param orderId
     * @param type  0:车外；1：车内
     * @return
     */
    @PostMapping("/uploadBeforeImage")
    public R uploadBeforeImage(MultipartFile file,HttpServletRequest request,
                               @RequestParam(value = "orderId",required = true) String orderId,
                               @RequestParam(value = "type",required = true) Integer type){

        long userId = (Long)request.getAttribute("userId");
        OrderEntity orderEntity = orderService.getOneByOrderId(orderId);
        if (orderEntity == null){
            return R.error("订单不存在");
        }else if(orderEntity.getOrderState() == 8){
            return R.error("订单已取消");
        }else if(orderEntity.getOrderState() == 7){
            return R.error("订单被拒绝,"+orderEntity.getRejectReason());
        }else if(orderEntity.getOrderState() == 4){
            return R.error("您已开始检车，请勿重复操作");
        }else if(orderEntity.getOrderState() == 5){
            return R.error("订单已完成");
        }else if(orderEntity.getOrderState() == 9){
            return R.error("订单处理失败");
        }else if(orderEntity.getOrderState() == 6){
            return R.error("已完成评论");
        }
        String filename =  userId+"_"+orderId;
        if (type == 0){
            filename = filename+PicSuffix.ORDER_OUTSIDE_PIC.getSuffix();
        }else {
            filename = filename+PicSuffix.ORDER_INSIDE_PIC.getSuffix();
        }
        File pic = new File(orderBeforePicPath+"/"+filename);
        if (pic.exists()){
            return R.error("图片已存在").put("userId",userId);
        }
        boolean res = FileUtils.upload(file,orderBeforePicPath,filename);
        if (res){
            return R.ok("上传成功").put("userId",userId);
        }
        return R.error("上传失败");

    }

    /**
     * 到站检车
     * @param checkCarForm
     * @return
     */
    @PostMapping("/checkCar")
    public R checkCar(@RequestBody CheckCarForm checkCarForm,HttpServletRequest request){

        ValidatorUtils.validateEntity(checkCarForm, CheckCarGroup.class);

        long userId = (Long)request.getAttribute("userId");

        OrderEntity order = orderService.getOneByOrderId(checkCarForm.getOrderId());
        if (order == null){
            return R.error("订单不存在");
        }
        String filename =  userId+"_"+order.getOrderId();
        String img_out = orderBeforePicPath+"/"+filename+PicSuffix.ORDER_OUTSIDE_PIC.getSuffix();
        String img_in = orderBeforePicPath+"/"+filename+PicSuffix.ORDER_INSIDE_PIC.getSuffix();
        if (!(new File(img_out)).exists()){
            return R.error("开始检车前,请先上传车外部照片");
        }else if (!(new File(img_in)).exists()){
            return R.error("开始检车前，请先上传车内部照片");
        }
        if(order.getOrderState() == 8){
            return R.error("订单已取消");
        }else if(order.getOrderState() == 7){
            return R.error("订单被拒绝,"+order.getRejectReason());
        }else if(order.getOrderState() == 4){
            return R.error("您已开始检车，请勿重复操作");
        }else if(order.getOrderState() == 5){
            return R.error("订单已完成");
        }else if(order.getOrderState() == 9){
            return R.error("订单处理失败");
        }else if(order.getOrderState() == 6){
            return R.error("已完成评论");
        }
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setUserId(userId);
        orderEntity.setOrderId(checkCarForm.getOrderId());
        orderEntity.setReceiver_name(checkCarForm.getReceiver_name());
        orderEntity.setReceive_call(checkCarForm.getReceiver_call());
        boolean b = orderService.updateOrderReceiver(orderEntity);
        if (b){
            return R.ok();
        }
        return R.error();


    }

    /**
     * 检车后上传照片
     * @param file
     * @param request
     * @param orderId
     * @param type  0:车外；1：车内
     * @return
     */
    @PostMapping("/uploadAfterImage")
    public R uploadAfterImage(MultipartFile file,HttpServletRequest request,
                               @RequestParam(value = "orderId",required = true) String orderId,
                               @RequestParam(value = "type",required = true) Integer type){

        long userId = (Long)request.getAttribute("userId");
        OrderEntity orderEntity = orderService.getOneByOrderId(orderId);
        if (orderEntity == null){
            return R.error("订单不存在！");
        }else if(orderEntity.getOrderState()<4){
            return R.error("未接单成功！");
        }
        String filename =  userId+"_"+orderId;
        if (type == 0){
            filename = filename+PicSuffix.ORDER_OUTSIDE_PIC.getSuffix();
        }else {
            filename = filename+PicSuffix.ORDER_INSIDE_PIC.getSuffix();
        }
        File pic = new File(orderAfterPicPath+"/"+filename);
        if (pic.exists()){
            return R.error("图片已存在").put("userId",userId);
        }
        boolean res = FileUtils.upload(file,orderAfterPicPath,filename);
        if (res){
            // 更新订单状态
            orderService.successOrder(orderId,userId);
            return R.ok("上传成功").put("userId",userId);
        }
        return R.error("上传失败");
    }



    /**
     * 完成检车
     * @param request
     * @param orderId
     * @return
     */
    @GetMapping("/successOrder")
    public R success(HttpServletRequest request,
                     @RequestParam(value = "orderId",required = true) String orderId){
        long userId = (Long)request.getAttribute("userId");
        OrderEntity orderEntity = orderService.getOneByOrderId(orderId);
        if (orderEntity == null){
            return R.error("订单不存在！");
        }
        String filename =  userId+"_"+orderId;
        String img_out = orderAfterPicPath+"/"+filename+PicSuffix.ORDER_OUTSIDE_PIC.getSuffix();
        String img_in = orderAfterPicPath+"/"+filename+PicSuffix.ORDER_INSIDE_PIC.getSuffix();
        if (!(new File(img_out)).exists()){
            return R.error("检车完成后，请先上传车外部照片");
        }else if (!(new File(img_in)).exists()){
            return R.error("检车完成后，请先上传车内部照片");
        }
        if (orderEntity.getOrderState()==4){

            boolean b = orderService.successOrder(orderId,userId);
            if (b){
                return R.ok();
            }else {
                return R.error();
            }

        }
        return R.error("无法执行此步骤");


    }

    /**
     * 订单评分评论
     * @param orderForm
     * @param request
     * @return
     */
    @PostMapping("/assess")
    public R assess(@RequestBody OrderForm orderForm, HttpServletRequest request){

        long userId = (Long)request.getAttribute("userId");

        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setUserId(userId);
        orderEntity.setOrderId(orderForm.getOrderId());
        orderEntity.setOrderScore(orderForm.getOrderScore());
        orderEntity.setOrderAssess(orderForm.getOrderAssess());
        orderEntity.setOrderState(6);

        boolean b = orderService.updateOrderAccess(orderEntity);
        if (b){
            return R.ok("评论成功");
        }
        return R.error("评论失败");

    }
}
